package com.carboy.launch.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.KeyguardManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.carboy.launch.TtsManager;
import com.carboy.launch.vo.AppInfo;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SynthesizerListener;

@SuppressLint("NewApi")
public class Tool {

	/**
	 * 获取版本号
	 **/
	public static String getVersionName(Context context) {
		String versionCode = null;
		PackageManager packageManager = context.getPackageManager();
		PackageInfo packInfo = null;
		try {
			packInfo = packageManager.getPackageInfo(context.getPackageName(),
					0);
			versionCode = packInfo.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dp2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 判断是否有网络连接
	 * */
	public static boolean isNetworkConnect(Context context) {

		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {

				return mNetworkInfo.isAvailable();
			}

		}
		return false;
	}

	/**
	 * 判断第三方应用包是否存在
	 * */
	public static boolean isPackageExists(Context mContext, String packageName) {
		try {
			PackageManager pm = mContext.getPackageManager();
			pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
			Log.i("TAG", "true");
			return true;
		} catch (NameNotFoundException e) {
			Log.i("TAG", "false");
			return false;
		}
	}

	/**
	 * 通过广播关闭指定应用
	 * 
	 * @param mContext
	 *            上下问
	 * @param packageName
	 *            包名
	 */
	public static void forceCloseApp(Context mContext, String packageName) {
		try {
			Intent mIntent = new Intent();
			mIntent.setAction("com.rmt.action.KILL_PACKAGE");
			mIntent.putExtra("kill_package_name", packageName);
			mContext.sendBroadcast(mIntent);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 唤醒屏幕
	 * 
	 * @param context
	 */
	public static void wakeUpScreen(Context context) {
		KeyguardManager km = null;
		boolean black = true;
		try {
			km = (KeyguardManager) context
					.getSystemService(Context.KEYGUARD_SERVICE);
			black = km.inKeyguardRestrictedInputMode();
			if (!black) {
				KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
				// 解锁
				kl.disableKeyguard();
				// 获取电源管理器对象
				PowerManager pm = (PowerManager) context
						.getSystemService(Context.POWER_SERVICE);
				// 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
				PowerManager.WakeLock wl = pm.newWakeLock(
						PowerManager.ACQUIRE_CAUSES_WAKEUP
								| PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
				// 点亮屏幕
				wl.acquire();
				// 释放
				wl.release();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 字符串是否为空
	 * 
	 * @param object
	 * 
	 * @return
	 */
	public static boolean isValidString(String str) {
		if (null != str && !"".equals(str.trim())) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * 恢复音量
	 */
	public static void setVolume(Context mContext, boolean play) {

		AudioManager mAudioManager = (AudioManager) mContext
				.getSystemService(Context.AUDIO_SERVICE);
		int curVol = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		// Toast.makeText(mContext, "当前音量"+curVol,3000).show();
		if (curVol == 0) {
			// 关闭静音
			if (play) {
				TtsManager.getInstance(mContext).playText("取消静音");
			}
			// 关闭静音
			mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
			mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);

		} else {
			// 静音
			if (play) {
				com.carboy.launch.IflyTTS.beginIflyTTS(mContext, "静音",
						new VoiceLinster(mAudioManager));
			} else {
				mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
			}
			mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

		}

	}

	static class VoiceLinster implements SynthesizerListener {
		private AudioManager mAudioManager;

		public VoiceLinster(AudioManager mAudioManager) {
			super();
			this.mAudioManager = mAudioManager;
		}

		@Override
		public void onBufferProgress(int arg0, int arg1, int arg2, String arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onCompleted(SpeechError arg0) {
			// TODO Auto-generated method stub
			mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
		}

		@Override
		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSpeakBegin() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSpeakPaused() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSpeakProgress(int arg0, int arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSpeakResumed() {
			// TODO Auto-generated method stub

		}

	}

	/**
	 * 打开蓝牙
	 * 
	 * @return 返回1，打开，返回2，蓝牙已经打开了 ！！！！！！！！！！！
	 */
	public static String openBluetooth() {

		try {
			// 打开蓝牙服务
			BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
					.getDefaultAdapter();
			if (mBluetoothAdapter == null) {
				return "未找到蓝牙硬件或驱动！";
			}
			// 如果没有打开则开启
			if (!mBluetoothAdapter.isEnabled()) {
				mBluetoothAdapter.enable();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "打开蓝牙出错";
		}
		return "已打开蓝牙";
	}

	/***
	 * 关闭蓝牙 ！！！！！！！！！！！！！
	 */
	public static String closeBluetooth() {

		try {
			BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
					.getDefaultAdapter();
			if (mBluetoothAdapter == null) {
				return "未找到蓝牙硬件或驱动！";
			}
			if (mBluetoothAdapter.isEnabled()) {
				mBluetoothAdapter.disable();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "关闭蓝牙出错";
		}
		return "已关闭蓝牙";

	}

	/*
	 * 利用java的反射机制,打开关闭网络
	 */
	public static void setMobileDataEnabled(boolean enabled, Context mcontext) {

		try {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) mcontext
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			Method method = mConnectivityManager.getClass().getMethod(
					"setMobileDataEnabled", Boolean.TYPE);
			if (!getMobileDataEnabled(mcontext)) {
				method.invoke(mConnectivityManager, enabled);
			}
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static boolean getMobileDataEnabled(Context mcontext) {
		try {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) mcontext
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			Method method = mConnectivityManager.getClass().getMethod(
					"getMobileDataEnabled");
			return (Boolean) method.invoke(mConnectivityManager);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 用来判断服务是否运行.
	 * 
	 * @param context
	 * @param className
	 *            判断的服务名字
	 * @return true 在运行 false 不在运行
	 */
	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(30);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

    /** 
     * 判断某个服务是否正在运行的方法 
     *  
     * @param mContext 
     * @param serviceName 
     *            是包名+服务的类名（例如：net.loonggg.testbackstage.TestService） 
     * @return true代表正在运行，false代表服务没有正在运行 
     */  
    public static boolean isServiceWork(Context mContext, String serviceName) {  
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningServiceInfo> myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    /**
	 * 
	 * @author James
	 * @Description 判断某服务是否在运行
	 * @param mContext
	 * @param className
	 * @return
	 */
	public static boolean isServiceWorked(Context mContext, String className) {
		ActivityManager myManager = (ActivityManager) mContext
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
				.getRunningServices(100);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString()
					.equals(className)) {
				return true;
			}
		}
		return false;
	}


	/**
	 * 
	 * @author James
	 * @Description 打开第三方app
	 * @param mContext
	 * @param pkg
	 *            包名
	 * @param cls
	 *            类名
	 * @return 是否打开成功
	 */
	public static boolean openApp(Context mContext, String pkg, String cls) {
		boolean openSucess = true;
		ComponentName componetName = new ComponentName(pkg, cls);
		try {
			Intent intent = new Intent();
			intent.setComponent(componetName);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
			openSucess = true;
		} catch (Exception e) {
			openSucess = false;
		}
		return openSucess;
	}

	/**
	 * 
	 * @author James
	 * @Description 启动其他进程的service
	 * @param mContext
	 * @param pkg
	 * @param cls
	 * @return
	 */
	public static boolean startService(Context mContext, String pkg, String cls) {
		boolean openSucess = true;
		ComponentName componetName = new ComponentName(pkg, cls);
		try {
			Intent intent = new Intent();
			intent.setComponent(componetName);
			mContext.startService(intent);
			openSucess = true;
		} catch (Exception e) {
			openSucess = false;
		}
		return openSucess;
	}

	/***
	 * 判断应用是否在最上层
	 * 
	 * @param mContext
	 * @param appName
	 *            Activity类名
	 * @return
	 */
	public static boolean isTopActivity(Context mContext, String appName) {
		boolean isTop = false;
		ActivityManager am = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		// 获取Task集合
		List<RunningTaskInfo> tasks = am.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			// 获取第一个组件
			ComponentName cn = tasks.get(0).topActivity;
			String name = cn.getClassName();
			if (cn.getClassName().contains(appName)) {
				isTop = true;
			}

		}
		return isTop;
	}

	/**
	 * @author James
	 * @Description 是否是usb调试模式
	 * @return true 开启调试，false 未开启调试
	 */
	public static boolean usbStatus(Context mContext) {
		boolean enableAdb = (Settings.Secure.getInt(
				mContext.getContentResolver(), Settings.Secure.ADB_ENABLED, 0) > 0);
		return enableAdb;
	}

	public static boolean isWifiConnected(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifiNetworkInfo = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (wifiNetworkInfo.isConnected()) {
			return true;
		}

		return false;
	}

	/**
	 * 获取全部app信息
	 */
	public static String getVersion(Context mContext, String pName) {
		String name = "";
		PackageManager pManager = mContext.getPackageManager();
		// 获取手机内所有应用
		List<PackageInfo> packlist = pManager.getInstalledPackages(0);

		for (int i = 0; i < packlist.size(); i++) {
			PackageInfo pak = (PackageInfo) packlist.get(i);

			// 判断是否为非系统预装的应用程序
			// 这里还可以添加系统自带的，这里就先不添加了，如果有需要可以自己添加
			// if()里的值如果<=0则为自己装的程序，否则为系统工程自带
			if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
				// 添加自己已经安装的应用程序
				if (pak.packageName.equals(pName)) {
					name = pak.versionName;
				}
			}
			if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) > 0) {
				if (pak.packageName.equals(pName)) {
					name = pak.versionName;
				}

			}
		}
		return name;

	}

	/**
	 * 
	 * @author James
	 * @Description 打开APP
	 * @param context
	 * @param pkg
	 * @param cls
	 */
	public static void startApp(Context context, String pkg, String cls) {
		ComponentName componetName = new ComponentName(pkg, cls);
		try {
			Intent intent = new Intent();
			intent.setComponent(componetName);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
		} catch (Exception e) {

		}
	}

	public static boolean isupdata(String url, String curVersion) {
		Map<String, String> map;
		try {
			map = ParseXmlService.parseXml(UrlResult.GetUrlStr(url));
			if (map != null) {
				String apkVersion = map.get("versionName");
				String apkName = map.get("appName");
				String apkDate = map.get("versionTime");
				if (!TextUtils.isEmpty(apkVersion)
						&& apkVersion.compareTo(curVersion) > 0) {

					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}

	public static boolean isupdata(Context mContext, String url) {

		return false;

	}

	/**
	 * 获取后台运行的程序是否含有车宝后台服务
	 */
	/**
	 * 判断app是否在运行
	 * 
	 * @param mContext
	 * @param packageName
	 *            包名
	 */
	public static boolean isRunBackground(Context mContext, String appName) {
		boolean isRun = false;
		try {
			// 获取activity管理对象
			ActivityManager activityManager = (ActivityManager) mContext
					.getSystemService(Context.ACTIVITY_SERVICE);
			// 获取所有正在运行的app
			List<RunningAppProcessInfo> appProcesses = activityManager
					.getRunningAppProcesses();
			// 遍历app，对于应用名称
			for (RunningAppProcessInfo appProcess : appProcesses) {
				if (appProcess.processName.equals(appName)) {

					Log.i("app", appName + "在运行");
					return true;
				}
			}
		} catch (Exception e) {
			isRun = false;
			e.printStackTrace();
		}
		return isRun;
	}

	/**
	 * 
	 * @author James
	 * @Description 恢复出厂，清除保存参数
	 */
	public static void restoreFactory(Context mContext) {
		// 恢复亮屏默认2分钟
		Settings.System.putInt(mContext.getContentResolver(),
				android.provider.Settings.System.SCREEN_OFF_TIMEOUT, 120000);
		// 音量
		AudioManager mAudioManager = (AudioManager) mContext
				.getSystemService(Context.AUDIO_SERVICE);
		mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
		int curVol = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		if (curVol == 0) {
			mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
		}
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 8, 0);
		// 亮度
		Settings.System.putInt(mContext.getContentResolver(),
				Settings.System.SCREEN_BRIGHTNESS, 200);

	}

	/***
	 * 判断SN号是否合法
	 * 
	 * @return
	 */
	public static boolean isValidSN(String sn) {
		String reg = "^[A-Za-z0-9]+$";
		if (StringUtils.isValidString(sn)) {
			if (sn.length() == 8 && sn.matches(reg)) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * 关闭wifi热点
	 */
	public static boolean setWifiApEnabled(Context context, WifiManager wifiManager,
			boolean enable) {
	    final ContentResolver cr = context.getContentResolver();
		boolean result = false;
		try {
			// 打开wifi服务
			// 通过反射调用设置热点
			Method method = wifiManager.getClass().getMethod(
					"setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
			// 返回热点打开状态
			result = (Boolean) method.invoke(wifiManager,
					wifiManager.getWifiApConfiguration(), enable);
			if(enable) {
			    Settings.Global.putInt(cr, Settings.Global.WIFI_SAVED_STATE, 1);
			} else {
			    Settings.Global.putInt(cr, Settings.Global.WIFI_SAVED_STATE, 0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = false;
		}

		return result;
	}

	// 添加wifi配置
	public static void addWifiApEnabled(WifiManager wifiManager,
			WifiConfiguration wifiConfiguration) {
		try {

			Method method = wifiManager.getClass().getMethod(
					"setWifiApConfiguration", WifiConfiguration.class);

			method.invoke(wifiManager, wifiConfiguration);
		} catch (Exception e) {
			Log.e("e", e + "");
		}
	}

	/**
	 * 根据app名字获取app包名
	 * 
	 * @param context
	 * @param text
	 * @return
	 */
	public static String getAppBg(Context context, String appName) {
		String appBg = "";

		// 获取已安装的程序
		ArrayList<AppInfo> list = getInstalledApps(context);
		// 遍历已安装程序
		for (int i = 0; i < list.size(); i++) {
			AppInfo appInfo = list.get(i);
			if (appInfo != null) {
				if (appInfo.getAppname().equals(appName)) {
					appBg = appInfo.getPname();
					return appBg;
				}
			}
		}

		return appBg;

	}

	/**
	 * 获取设备装的app应用信息
	 * 
	 * @param context
	 * @return
	 */
	public static ArrayList<AppInfo> getInstalledApps(Context context) {

		ArrayList<AppInfo> res = new ArrayList<AppInfo>();
		// 获取手机应用的集合
		List<PackageInfo> packs = context.getPackageManager()
				.getInstalledPackages(0);
		for (int i = 0; i < packs.size(); i++) {
			PackageInfo p = packs.get(i);
			// 定义应用bean对象
			AppInfo newInfo = new AppInfo();
			// 应用名
			newInfo.setAppname(p.applicationInfo.loadLabel(
					context.getPackageManager()).toString());
			// 包名
			newInfo.setPname(p.packageName);
			// 获取清单文件的versionName版本名
			newInfo.setVersionName(p.versionName);
			// 获取清单文件的versionCode版本号
			newInfo.setVersionCode(p.versionCode);
			res.add(newInfo);
		}
		return res;
	}

	/**
	 * 
	 * @author James
	 * @Description 点亮屏幕
	 * @param mContext
	 *            ！！！暂时没用！！！语音调用处理了
	 */
	public static void screenOnbyWakeUp(Context mContext) {
		PowerManager mPowerManager = (PowerManager) mContext
				.getSystemService(Context.POWER_SERVICE);
		//mPowerManager.setBacklightBrightnessOff(false);
		mContext.sendBroadcast(new Intent(Intent.ACTION_SCREEN_ON));
	}
}
